package com.yoomiito.app.ui.anyview.videoclip

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.*
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.home.VideoClipInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.utils.*
import com.yoomiito.app.utils.wx.WXUtils
import com.yoomiito.app.widget.dialog.CommentDialog
import com.yoomiito.app.widget.dialog.GoodsListDialog
import com.yoomiito.app.widget.dialog.ShareBottomDialog_1
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.item_coupon_view.view.*
import kotlinx.android.synthetic.main.item_goods_9.view.*
import kotlinx.android.synthetic.main.item_video_clip_bottom.view.*
import java.util.concurrent.TimeUnit

class VideoClipBottomView(val context: BaseActivity<*>, var videoInfo: VideoClipInfo?) : LinearLayout(context) {

    init {
        LayoutInflater.from(context).inflate(R.layout.item_video_clip_bottom, this, true)
        initView()
    }

    private fun initView() {
        div.visibility = View.GONE
        buy.visibility = View.GONE
        val lp = goodsPicIv.layoutParams as LayoutParams
        val width = DensityUtil.dp2px(88f)
        lp.height = width
        lp.width = width
        shopBag.setOnClickListener {
            showGoodsDialog()
        }
        comment.setOnClickListener {
            if (App.mAppConfig.isLogin) {
                showComment()
            } else {
//                AllUtils.toLogin(context, AllCode.LoginIn)
                LoginUtils.toOneKeyLogin(context)
            }
        }
        like.setOnClickListener {
            if (App.mAppConfig.isLogin) {
                videoLike()
            } else {
//                AllUtils.toLogin(context, AllCode.LoginIn)
                LoginUtils.toOneKeyLogin(context)
            }
        }

        forward.setOnClickListener {
            if (App.mAppConfig.isLogin) {
                showShareDialog()
            } else {
                LoginUtils.toOneKeyLogin(context)
//                AllUtils.toLogin(context, AllCode.LoginIn)
            }
        }
        updateInfo(videoInfo)
    }

    private fun showShareDialog() {
        val shareDialog = ShareBottomDialog_1(context)
        shareDialog.setOnShareItemClickListener { i ->
            AllUtils.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe { aBoolean ->
                        if (aBoolean!!)
                            context.showLoading()
                        val path = Environment.getExternalStorageDirectory().path + "/DCIM/video_" + DateUtils.current() + ".mp4"
                        //下载视频
                        DownloadUtils.download(path, videoInfo?.video!!) {
                            context.dismissLoading()
                            when (i) {
                                1, 2 -> {
                                    WXUtils.openWX(context)
                                }//微信好友 //朋友圈
                                3 -> {
                                    "保存成功".showToast()
                                }//保存
                            }
                            shareDialog.dismiss()
                            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                            val contentUri = Uri.fromFile(it)
                            mediaScanIntent.data = contentUri
                            context.sendBroadcast(mediaScanIntent)
                        }
                    }
            postShare(videoInfo!!.id)
            videoInfo?.share_num = (videoInfo?.share_num!!.toInt() + 1).toString()
            forwardSizeTv.text = if (null == videoInfo || videoInfo?.share_num!!.isEmptyOr0()) "转发" else videoInfo?.share_num!!.formatNum()
        }
        shareDialog.show()
    }

    private fun postShare(id: String) {
        YmApi.getYmService()
                .videoShare(id)
                .compose(context.bindToLifecycle())
                .compose(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                    override fun onSuccess(t: BaseModel<*>?) {
                    }

                    override fun onFail(error: ApiException?) {
                    }

                })
    }

    private fun videoLike() {
        YmApi.getYmService()
                .videoLike(videoInfo?.id)
                .compose(context.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                    override fun onSuccess(t: BaseModel<*>?) {
                        videoInfo?.like_num = if (likeSv.isSelected) {//取消点赞
                            (videoInfo?.like_num!!.toLong() - 1).toString()
                        } else { //点赞
                            (videoInfo?.like_num!!.toLong() + 1).toString()
                        }
                        likeSizeTv.text = if (null == videoInfo || videoInfo?.like_num!!.isEmptyOr0()) "点赞" else videoInfo?.like_num?.formatNum()
                        likeSv.setSelect(!likeSv.isSelected)
                    }

                    override fun onFail(error: ApiException?) {
                        error?.msg?.strFilter { it.isNullOrEmpty() }.let { it?.showToast() }
                    }

                })
    }

    private fun showGoodsTip() {
        videoTitleTv.visibility = View.GONE
        rollingMsgParentView.visibility = View.GONE
        val product = videoInfo?.videoOtherInfo?.product?.get(0)
        if (product != null) {
            showGoodsLl.visibility = View.VISIBLE
            showGoodsLl.setOnClickListener {
                RouterUtils.toGoodsDetail(context, product.id, DataUtils.getGoodsType(product.type))
            }
            val lp = goodsCouponView.layoutParams as LayoutParams
            lp.topMargin = DensityUtil.dp2px(8f)

            ImageLoader.getInstance().into(context, product?.image, goodsPicIv)

            goodsTitleTv.text = if (product.type == "1") SpannableUtils.getIconAndText(product?.title, ResUtil.getDrawable(DataUtils.ivType(product.source))) else product?.title
//            awardView.visibility = if (product?.buyAwardPrice.isEmptyOr0()) View.INVISIBLE else View.VISIBLE
//            awardView.setText(product?.buyAwardPrice.removeDecimalPoint())
//            couponView.visibility = if (product?.couponPrice.isEmptyOr0()) View.INVISIBLE else View.VISIBLE
//            couponView.setText(product?.couponPrice.removeDecimalPoint())
            awardView.visibility = View.INVISIBLE
            couponView.visibility = View.INVISIBLE
            val lp1 = goodsPriceLl.layoutParams as LayoutParams
            lp1.topMargin = DensityUtil.dp2px(0f)
            val priceT = product.discountPrice.removeDecimalPoint()
            val oldPriceT = product.zkFinalPrice.removeDecimalPoint()
            goodsPriceTv.text = (if (oldPriceT.isEmptyOr0() || oldPriceT == priceT) "¥$priceT " else "¥$priceT ¥$oldPriceT").goodsPrice(priceT)
            goodsPriceTv.setPadding(0, 0, 0, DensityUtil.dp2px(4f))

            Observable.timer(2, TimeUnit.SECONDS)
                    .compose(context.bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        showGoodsLl.visibility = View.GONE
                        showGoodsInfo()

                    }
        } else {
            showGoodsLl.visibility = View.GONE
            showGoodsInfo()
        }
    }

    /**
     * 显示滚动列表 商品标题
     */
    private fun showGoodsInfo() {
        videoTitleTv.visibility = View.VISIBLE
        rollingMsgParentView.visibility = View.VISIBLE
        videoTitleTv.text = videoInfo?.title
        if (rollingMsgParentView.childCount == 0) {
            val rollingView = RollingMsgView(context)
            rollingMsgParentView.addView(rollingView,
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
            if (videoInfo?.videoOtherInfo != null) {
                rollingView.setNewDatas(videoInfo?.videoOtherInfo!!.orderList)
            }
        } else {
            val rollingView = rollingMsgParentView.getChildAt(0) as RollingMsgView
            if (videoInfo?.videoOtherInfo != null) {
                rollingView.setNewDatas(videoInfo?.videoOtherInfo!!.orderList)
            }
        }

    }

    fun updateInfo(videoInfo: VideoClipInfo?) {
        this.videoInfo = videoInfo
        videoTitleTv.text = videoInfo?.title
        likeSv.setSelect(videoInfo?.videoOtherInfo?.is_like == 1)
        commentSizeTv.text = if (null == videoInfo?.videoOtherInfo || videoInfo?.videoOtherInfo.comment_num.isEmptyOr0()) "评论" else videoInfo?.videoOtherInfo.comment_num.formatNum()
        likeSizeTv.text = if (null == videoInfo || videoInfo.like_num.isEmptyOr0()) "点赞" else videoInfo.like_num.formatNum()
        forwardSizeTv.text = if (null == videoInfo || videoInfo.share_num.isEmptyOr0()) "转发" else videoInfo.share_num.formatNum()
        shopBag.visibility = if (videoInfo?.videoOtherInfo?.product == null || videoInfo?.videoOtherInfo?.product?.size == 0) View.GONE else View.VISIBLE
        val show = if (videoInfo?.videoOtherInfo?.product == null || videoInfo?.videoOtherInfo?.product?.size == 0) View.GONE else View.VISIBLE
        shopBag.visibility = show
        shopBagSizeTv.visibility = show
        shopBagSizeTv.text = videoInfo?.videoOtherInfo?.product_num
        showGoodsTip()

    }

    private fun showGoodsDialog() {
        val dialog = GoodsListDialog(context, videoInfo?.videoOtherInfo?.product)
        dialog.show()
    }

    private fun showComment() {
        val commentDialog = CommentDialog(context, videoInfo) {
            val size = if (it == 0) "评论" else it.toString().formatNum()
            commentSizeTv.text = size
        }
        commentDialog.showDialog()
    }
}